package com.sina.finance.api.framework.permission.timestamp;

import com.sina.finance.api.framework.utils.ParameterParser;

import java.util.Map;
import java.util.Properties;

/**
 * @File name : Optional
 * @Description :
 * @Creator : cuiyong
 * @CreateTime : 15/12/1 14:38
 * @Version : 1.0
 * @Update records:
 * 1.0 15/12/1 by cuiyong: Created
 * All rights served : SINA Corporation
 */
public class OptionalWebTimeStampChecker{
    private TimeStampChecker timeStampChecker;
    private String optionalTimeStampCheckPropKey;

    private String timeStampParamKey;
    private Properties timeStampCheckProperties;

    public OptionalWebTimeStampChecker(TimeStampChecker timeStampChecker, String timeStampParamKey, Properties timeStampCheckProperties, String optionalTimeStampCheckPropKey) {
        this.timeStampChecker = timeStampChecker;
        this.timeStampParamKey = timeStampParamKey;
        this.optionalTimeStampCheckPropKey = optionalTimeStampCheckPropKey;
        this.timeStampCheckProperties = timeStampCheckProperties;
    }

    public boolean checkTimeStamp(Map<String, String[]> requestParams, String id) {
        ParameterParser instance = ParameterParser.createInstance(requestParams);
        Long timeStamp = instance.getLong(timeStampParamKey);
        if (isInOptionalList(id)) {
            if (timeStamp == null) {
                timeStamp = System.currentTimeMillis();
            }
        }

        return timeStampChecker.timeStampCheck(timeStamp);
    }

    private boolean isInOptionalList(String id) {
        String property = timeStampCheckProperties.getProperty(optionalTimeStampCheckPropKey);
        String[] split = property.split(",");

        for (String s : split) {
            if (s.equals(id)) {
                return true;
            }
        }

        return false;
    }

}
